String methods help you to work with strings.
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
The length property returns the length of a string:
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
Try it Yourself »
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Try it Yourself »
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
JavaScript counts positions from zero.
0 is the first position in a
string, 1 is the second, 2 is the third ...
Both methods accept a second parameter as the starting position for the search:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate",15);
Try it Yourself »
The search() method searches a string for a specified value and returns the position of the match:
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Try it Yourself »
The two methods, indexOf() and search(), are equal?
They accept the same arguments (parameters), and return the same value?
The two methods are quite equal. These are the differences:
You will learn more about regular expressions in a later chapter.
There are 3 methods for extracting a part of a string:
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position), and the ending index (position).
This example slices out a portion of a string from position 7 to position 13:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
The result of res will be:
Banana
Try it Yourself »
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);
The result of res will be:
Banana
Try it Yourself »
If you omit the second parameter, the method will slice out the rest of the string:
or, counting from the end:
Negative positions do not work in Internet Explorer 8 and earlier.
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
The result of res will be:
Banana
Try it Yourself »
If you omit the second parameter, substring() will slice out the rest of the string.
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
The result of res will be:
Banana
Try it Yourself »
If the first parameter is negative, the position counts from the end of the string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
The replace() method replaces a specified value with another value in a string:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
Try it Yourself »
The replace() method does not change the string it is called on. It returns a new string.
By default, the replace() function replaces only the first match:
str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
To replace all matches, use a regular expression with a /g flag (global match):
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");
By default, the replace() function is case sensitive. Writing MICROSOFT (with upper-case) will not work:
str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "W3Schools");
To replace case insensitive, use a regular expression with an /i flag (insensitive):
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");
You will learn a lot more about regular expressions in the chapter JavaScript Regular Expressions.
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
Try it Yourself »
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1
converted to lower
Try it Yourself »
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
Try it Yourself »
The concat() method can be used instead of the plus operator. These two lines do the same:
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
There are 2 safe methods for extracting string characters:
The charAt() method returns the character at a specified index (position) in a string:
The charCodeAt() method returns the unicode of the character at a specified index in a string:
You might have seen code like this, accessing a string as an array:
var str = "HELLO WORLD";
str[0]; // returns H
This is unsafe and unpredictable:
If you want to read a string as an array, convert it to an array first.
A string can be converted to an array with the split() method:
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Try it Yourself »
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:
A JavaScript string stores a series of characters like "John Doe".
A string can be any text inside double or single quotes:
String indexes are zero-based: The first character is in position 0, the second in 1, and so on.
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
Property | Description |
---|---|
constructor | Returns the string's constructor function |
length | Returns the length of a string |
prototype | Allows you to add properties and methods to an object |
Method | Description |
---|---|
charAt() | Returns the character at the specified index (position) |
charCodeAt() | Returns the Unicode of the character at the specified index |
concat() | Joins two or more strings, and returns a new joined strings |
endsWith() | Checks whether a string ends with specified string/characters |
fromCharCode() | Converts Unicode values to characters |
includes() | Checks whether a string contains the specified string/characters |
indexOf() | Returns the position of the first found occurrence of a specified value in a string |
lastIndexOf() | Returns the position of the last found occurrence of a specified value in a string |
localeCompare() | Compares two strings in the current locale |
match() | Searches a string for a match against a regular expression, and returns the matches |
repeat() | Returns a new string with a specified number of copies of an existing string |
replace() | Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced |
search() | Searches a string for a specified value, or regular expression, and returns the position of the match |
slice() | Extracts a part of a string and returns a new string |
split() | Splits a string into an array of substrings |
startsWith() | Checks whether a string begins with specified characters |
substr() | Extracts the characters from a string, beginning at a specified start position, and through the specified number of character |
substring() | Extracts the characters from a string, between two specified indices |
toLocaleLowerCase() | Converts a string to lowercase letters, according to the host's locale |
toLocaleUpperCase() | Converts a string to uppercase letters, according to the host's locale |
toLowerCase() | Converts a string to lowercase letters |
toString() | Returns the value of a String object |
toUpperCase() | Converts a string to uppercase letters |
trim() | Removes whitespace from both ends of a string |
valueOf() | Returns the primitive value of a String object |
All string methods return a new value. They do not change the original variable.
The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.
These are not standard methods, and may not work as expected in all browsers.
Method | Description |
---|---|
anchor() | Creates an anchor |
big() | Displays a string using a big font |
blink() | Displays a blinking string |
bold() | Displays a string in bold |
fixed() | Displays a string using a fixed-pitch font |
fontcolor() | Displays a string using a specified color |
fontsize() | Displays a string using a specified size |
italics() | Displays a string in italic |
link() | Displays a string as a hyperlink |
small() | Displays a string using a small font |
strike() | Displays a string with a strikethrough |
sub() | Displays a string as subscript text |
sup() | Displays a string as superscript text |